import React, { useEffect, useState } from 'react';
import { Spin } from 'antd';
import { 
  UserOutlined, 
  UsergroupAddOutlined,
  RiseOutlined,
  FieldTimeOutlined,
  CalendarOutlined 
} from '@ant-design/icons';
import { getUserStatistics } from '../../../api/userController.ts';
import { getCategoryStatistics } from '../../../api/bookController.ts';
import { getCategoryStatistics as getPostCategoryStatistics } from '../../../api/communityPostController';
import { Column } from '@ant-design/charts';
import { withAdminAuth } from '../../../components/AdminAuth';

interface UserStatistics {
  totalUsers: string;
  todayNewUsers: string;
  threeDaysNewUsers: string;
  weekNewUsers: string;
  monthNewUsers: string;
}

interface CategoryStatistics {
  id: string;
  categorycode: string;
  categorynamezh: string;
  bookCount: string;
}

interface PostCategoryStatistics {
  totalCount: string;
  categoryList: Array<{
    id: string;
    categoryCode: string;
    categoryNameZh: string;
    postCount: string;
  }>;
}

function Home() {
  const [statistics, setStatistics] = useState<UserStatistics | null>(null);
  const [categoryStats, setCategoryStats] = useState<CategoryStatistics[]>([]);
  const [postStats, setPostStats] = useState<PostCategoryStatistics | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [userResponse, categoryResponse, postResponse] = await Promise.all([
          getUserStatistics(),
          getCategoryStatistics(),
          getPostCategoryStatistics()
        ]);
        
        if (userResponse.code === 200) {
          setStatistics(userResponse.data);
        }
        
        if (categoryResponse.code === 200) {
          setCategoryStats(categoryResponse.data);
        }

        if (postResponse.code === 200) {
          setPostStats(postResponse.data);
        }
      } catch (error) {
        console.error('获取数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-[200px]">
        <Spin size="large" />
      </div>
    );
  }

  const statisticItems = [
    {
      title: '总用户数',
      value: statistics?.totalUsers,
      icon: <UserOutlined className="text-2xl" />,
      bgColor: 'bg-blue-50',
      textColor: 'text-blue-500',
      borderColor: 'border-blue-100'
    },
    {
      title: '今日新增',
      value: statistics?.todayNewUsers,
      icon: <UsergroupAddOutlined className="text-2xl" />,
      bgColor: 'bg-green-50',
      textColor: 'text-green-500',
      borderColor: 'border-green-100'
    },
    {
      title: '近三日新增',
      value: statistics?.threeDaysNewUsers,
      icon: <RiseOutlined className="text-2xl" />,
      bgColor: 'bg-yellow-50',
      textColor: 'text-yellow-500',
      borderColor: 'border-yellow-100'
    },
    {
      title: '本周新增',
      value: statistics?.weekNewUsers,
      icon: <FieldTimeOutlined className="text-2xl" />,
      bgColor: 'bg-purple-50',
      textColor: 'text-purple-500',
      borderColor: 'border-purple-100'
    },
    {
      title: '本月新增',
      value: statistics?.monthNewUsers,
      icon: <CalendarOutlined className="text-2xl" />,
      bgColor: 'bg-pink-50',
      textColor: 'text-pink-500',
      borderColor: 'border-pink-100'
    }
  ];

  const totalBooks = categoryStats.find(item => item.categorycode === 'all')?.bookCount || '0';
  const totalPosts = postStats?.totalCount || '0';

  return (
    <div className="space-y-6">
      {/* 用户统计部分 */}
      <div>
        <h2 className="text-2xl font-bold mb-4">用户统计</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
          {statisticItems.map((item, index) => (
            <div
              key={index}
              className={`${item.bgColor} ${item.borderColor} border rounded-lg p-4 transition-transform hover:scale-105 cursor-pointer flex flex-col items-center`}
            >
              <div className={`${item.textColor} flex items-center mb-2`}>
                {item.icon}
                <span className="ml-2 text-lg font-medium">{item.title}</span>
              </div>
              <div className={`${item.textColor} text-3xl font-bold text-center`}>
                {item.value || '0'}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 图表区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-white p-6 rounded-lg shadow h-[600px]">
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-lg font-medium">图书分类统计</h3>
            <div className="text-gray-500">
              总图书数：<span className="text-blue-500 font-bold text-xl">{totalBooks}</span>
            </div>
          </div>
          <Column 
            height={500}
            data={categoryStats
              .filter(item => item.categorycode !== 'all')
              .map(item => ({
                category: item.categorynamezh,
                value: parseInt(item.bookCount)
              }))}
            xField="category"
            yField="value"
            label={{
              position: 'middle',
              style: {
                fill: '#FFFFFF',
                opacity: 0.6,
              },
            }}
            xAxis={{
              label: {
                autoRotate: false,
                autoHide: false,
                autoEllipsis: true,
                width: 100,
                style: {
                  fontSize: 12,
                }
              }
            }}
            meta={{
              value: {
                alias: '图书数量'
              }
            }}
            color="#1890ff"
            columnStyle={{
              radius: [4, 4, 0, 0]
            }}
            minColumnWidth={20}
            maxColumnWidth={40}
          />
        </div>
        <div className="bg-white p-6 rounded-lg shadow h-[600px]">
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-lg font-medium">帖子分类统计</h3>
            <div className="text-gray-500">
              总帖子数：<span className="text-green-500 font-bold text-xl">{totalPosts}</span>
            </div>
          </div>
          <Column 
            height={500}
            data={postStats?.categoryList.map(item => ({
              category: item.categoryNameZh,
              value: parseInt(item.postCount)
            })) || []}
            xField="category"
            yField="value"
            label={{
              position: 'middle',
              style: {
                fill: '#FFFFFF',
                opacity: 0.6,
              },
            }}
            xAxis={{
              label: {
                autoRotate: false,
                autoHide: false,
                autoEllipsis: true,
                width: 100,
                style: {
                  fontSize: 12,
                }
              }
            }}
            meta={{
              value: {
                alias: '帖子数量'
              }
            }}
            color="#52c41a"
            columnStyle={{
              radius: [4, 4, 0, 0]
            }}
            minColumnWidth={20}
            maxColumnWidth={40}
          />
        </div>
      </div>
    </div>
  );
}

export default withAdminAuth(Home);